from PyQt6.QtWidgets import QWidget, QVBoxLayout, QLabel, QSizeGrip, QColorDialog
from PyQt6.QtCore import Qt, QTimer, QDateTime, QLocale
from PyQt6.QtGui import QPainter, QColor, QFont, QPen, QFontDatabase, QFontMetrics
import os
import sys

class DateClockWidget(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.text_color = QColor(0, 130, 0)  # 默认颜色
        self.show_border = False  # 添加边框显示标志
        self.initUI()
        
    def initUI(self):
        # 设置窗口标志
        self.setWindowFlags(Qt.WindowType.FramelessWindowHint | 
                          Qt.WindowType.WindowStaysOnTopHint |
                          Qt.WindowType.Tool)  # Tool窗口类型在任务栏不显示
        
        # 设置窗口透明背景
        self.setAttribute(Qt.WidgetAttribute.WA_TranslucentBackground)
        
        # 加载数字字体
        try:
            # 检查是否是打包后的环境
            if getattr(sys, 'frozen', False):
                # 如果是打包后的环境，使用 _MEIPASS
                base_path = sys._MEIPASS
            else:
                # 如果是开发环境，使用相对路径
                base_path = os.path.dirname(os.path.dirname(__file__))
                
            font_path = os.path.join(base_path, 'resources', 'digital-7-mono-3.ttf')
            font_id = QFontDatabase.addApplicationFont(font_path)
            if font_id != -1:
                self.font_family = QFontDatabase.applicationFontFamilies(font_id)[0]
            else:
                print(f"Error: Could not load font file from {font_path}")
                self.font_family = 'monospace'
        except Exception as e:
            print(f"Font loading error: {str(e)}")
            self.font_family = 'monospace'
            
        # 创建布局
        layout = QVBoxLayout(self)
        layout.setContentsMargins(10, 10, 10, 10)
        layout.setSpacing(5)  # 减小间距
        
        # 创建时间标签
        self.time_label = QLabel()
        self.time_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        # 创建日期标签
        self.date_label = QLabel()
        self.date_label.setAlignment(Qt.AlignmentFlag.AlignCenter)
        
        # 设置中文locale
        self.locale = QLocale(QLocale.Language.Chinese)
        
        # 添加到布局
        layout.addWidget(self.time_label)
        layout.addWidget(self.date_label)
        
        # 添加大小调整手柄
        self.size_grip = QSizeGrip(self)
        self.size_grip.setStyleSheet("background: transparent;")
        
        # 创建关闭按钮
        self.close_button = QLabel("×", self)  # 使用 × 作为关闭图标
        self.close_button.setFixedSize(20, 20)
        self.close_button.setStyleSheet(f"""
            QLabel {{
                color: {self.text_color.name()};
                background-color: rgba(255, 255, 255, 0.1);
                border-radius: 10px;
                font-size: 16px;
                font-weight: bold;
            }}
            QLabel:hover {{
                background-color: rgba(255, 0, 0, 0.2);
                color: #FF0000;
            }}
        """)
        self.close_button.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.close_button.hide()  # 初始隐藏
        
        # 创建拖动手柄
        self.drag_handle = QLabel("⇱", self)  # 使用右上箭头作为拖动图标
        self.drag_handle.setFixedSize(20, 20)
        self.drag_handle.setStyleSheet(f"""
            QLabel {{
                color: {self.text_color.name()};
                background-color: rgba(255, 255, 255, 0.1);
                border-radius: 10px;
                font-size: 12px;
                font-weight: bold;
            }}
            QLabel:hover {{
                background-color: rgba(255, 255, 255, 0.2);
            }}
        """)
        self.drag_handle.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.drag_handle.hide()  # 初始隐藏
        
        # 创建设置按钮
        self.settings_button = QLabel("⚙", self)  # 使用齿轮图标
        self.settings_button.setFixedSize(20, 20)
        self.settings_button.setStyleSheet(f"""
            QLabel {{
                color: {self.text_color.name()};
                background-color: rgba(255, 255, 255, 0.1);
                border-radius: 10px;
                font-size: 12px;
                font-weight: bold;
            }}
            QLabel:hover {{
                background-color: rgba(255, 255, 255, 0.2);
            }}
        """)
        self.settings_button.setAlignment(Qt.AlignmentFlag.AlignCenter)
        self.settings_button.hide()  # 初始隐藏
        
        # 设置定时器更新时间
        self.timer = QTimer(self)
        self.timer.timeout.connect(self.update_time)
        self.timer.start(1000)  # 每秒更新一次
        
        # 更新初始时间
        self.update_time()
        
        # 设置最小尺寸和固定初始大小
        self.setMinimumSize(1000, 300)
        self.resize(1000, 300)  # 设置初始大小
        
        # 初始化拖动相关变量
        self.dragging = False
        self.drag_position = None
        
    def showEvent(self, event):
        """在窗口显示时确保窗口居中"""
        super().showEvent(event)
        
        # 获取屏幕和窗口几何信息
        screen = self.screen()
        screen_geometry = screen.geometry()
        
        # 计算居中位置
        x = (screen_geometry.width() - self.width()) // 2
        
        # 移动窗口到居中位置，保持在顶部
        self.move(x, 0)
        
    def update_time(self):
        current = QDateTime.currentDateTime()
        
        # 更新时间标签，减小间距
        time_text = current.toString("HH:mm:ss")  # 移除额外的空格
        self.time_label.setText(time_text)
        
        # 更新日期标签（使用中文格式）
        date = current.date()
        # 使用英文星期缩写
        weekdays = ['MON', 'TUE', 'WED', 'THU', 'FRI', 'SAT', 'SUN']
        weekday = weekdays[date.dayOfWeek() - 1]  # dayOfWeek() 返回 1-7
        # 对于数字部分使用英文格式，保持数字的显示效果
        date_text = f"{date.year()}-{date.month():02d}-{date.day():02d} {weekday}"
        self.date_label.setText(date_text)
        
        # 动态调整字体大小
        self.adjust_font_sizes()
        
    def adjust_font_sizes(self):
        # 设置最小字体大小
        MIN_FONT_SIZE = 12
        
        # 调整时间标签字体大小，增大字体比例
        time_height = max(MIN_FONT_SIZE, int(self.height() * 0.7))  # 确保至少有最小高度
        time_font = QFont(self.font_family)
        time_font.setPixelSize(time_height)
        
        # 确保文本宽度不超过控件宽度
        metrics = QFontMetrics(time_font)
        text_width = metrics.horizontalAdvance(self.time_label.text())
        if text_width > self.width() - 40:  # 留出更多边距
            scale_factor = (self.width() - 40) / text_width
            new_size = max(MIN_FONT_SIZE, int(time_height * scale_factor))
            time_font.setPixelSize(new_size)
            
        # 更新时间标签样式，包含字体大小
        time_style = f"""
            QLabel {{
                color: {self.text_color.name()};
                font-family: '{self.font_family}';
                font-size: {time_font.pixelSize()}px;
            }}
        """
        self.time_label.setStyleSheet(time_style)
        
        # 调整日期标签字体大小
        date_height = max(MIN_FONT_SIZE, int(self.height() * 0.25))  # 确保至少有最小高度
        date_font = QFont(self.font_family)  # 使用相同的7段字体
        date_font.setPixelSize(date_height)
        
        # 确保文本宽度不超过控件宽度
        metrics = QFontMetrics(date_font)
        text_width = metrics.horizontalAdvance(self.date_label.text())
        if text_width > self.width() - 40:  # 留出更多边距
            scale_factor = (self.width() - 40) / text_width
            new_size = max(MIN_FONT_SIZE, int(date_height * scale_factor))
            date_font.setPixelSize(new_size)
            
        # 更新日期标签样式
        date_style = f"""
            QLabel {{
                color: {self.text_color.name()};
                font-family: '{self.font_family}';
                font-size: {date_font.pixelSize()}px;
                letter-spacing: 5px;  /* 增加字符间距 */
            }}
        """
        self.date_label.setStyleSheet(date_style)
        
    def update_colors(self):
        # 为时间标签设置样式（包含字体和颜色）
        time_style = f"""
            QLabel {{
                color: {self.text_color.name()};
                font-family: '{self.font_family}';
            }}
        """
        self.time_label.setStyleSheet(time_style)
        
        # 为日期标签设置样式（使用相同的7段字体）
        date_style = f"""
            QLabel {{
                color: {self.text_color.name()};
                font-family: '{self.font_family}';
                letter-spacing: 5px;  /* 增加字符间距 */
            }}
        """
        self.date_label.setStyleSheet(date_style)
        
        # 更新按钮样式
        button_style = f"""
            QLabel {{
                color: {self.text_color.name()};
                background-color: rgba(255, 255, 255, 0.1);
                border-radius: 10px;
                font-size: 12px;
                font-weight: bold;
            }}
            QLabel:hover {{
                background-color: rgba(255, 255, 255, 0.2);
            }}
        """
        
        # 关闭按钮有特殊的样式
        close_style = f"""
            QLabel {{
                color: {self.text_color.name()};
                background-color: rgba(255, 255, 255, 0.1);
                border-radius: 10px;
                font-size: 16px;
                font-weight: bold;
            }}
            QLabel:hover {{
                background-color: rgba(255, 0, 0, 0.2);
                color: #FF0000;
            }}
        """
        
        self.close_button.setStyleSheet(close_style)
        self.drag_handle.setStyleSheet(button_style)
        self.settings_button.setStyleSheet(button_style)
        
        self.update()  # 更新边框

    def paintEvent(self, event):
        painter = QPainter(self)
        painter.setRenderHint(QPainter.RenderHint.Antialiasing)
        
        # 绘制半透明背景
        painter.fillRect(self.rect(), QColor(0, 0, 0, 30))
        
        # 只在鼠标悬停时绘制边框
        if self.show_border:
            pen = QPen(self.text_color)
            pen.setWidth(2)
            painter.setPen(pen)
            painter.drawRect(self.rect().adjusted(1, 1, -1, -1))

    def event(self, event):
        # 不再阻止所有鼠标事件
        return super().event(event)

    def mousePressEvent(self, event):
        if event.button() == Qt.MouseButton.LeftButton:
            # 检查点击是否在各个按钮上
            if self.close_button.geometry().contains(event.position().toPoint()):
                self.close()  # 关闭窗口
            elif self.settings_button.geometry().contains(event.position().toPoint()):
                self.show_color_dialog()
            elif self.drag_handle.geometry().contains(event.position().toPoint()):
                self.dragging = True
                self.drag_position = event.globalPosition().toPoint() - self.frameGeometry().topLeft()
            event.accept()

    def mouseMoveEvent(self, event):
        if event.buttons() & Qt.MouseButton.LeftButton and self.dragging:
            self.move(event.globalPosition().toPoint() - self.drag_position)
            event.accept()

    def mouseReleaseEvent(self, event):
        if event.button() == Qt.MouseButton.LeftButton:
            self.dragging = False
            event.accept()

    def enterEvent(self, event):
        # 显示所有控制按钮
        self.close_button.show()
        self.drag_handle.show()
        self.settings_button.show()
        self.close_button.raise_()
        self.drag_handle.raise_()
        self.settings_button.raise_()
        # 将按钮移动到正确位置
        self.close_button.move(5, 5)  # 左上角
        self.drag_handle.move(self.width() - 25, 5)  # 右上角
        self.settings_button.move(self.width() - 25, self.height() - 25)  # 右下角
        # 显示边框
        self.show_border = True
        self.update()
        
    def leaveEvent(self, event):
        # 如果鼠标不在任何按钮上，则隐藏所有按钮
        if not any(btn.underMouse() for btn in [self.close_button, self.drag_handle, self.settings_button]):
            self.close_button.hide()
            self.drag_handle.hide()
            self.settings_button.hide()
            # 隐藏边框
            self.show_border = False
            self.update()

    def resizeEvent(self, event):
        super().resizeEvent(event)
        # 更新大小调整手柄的位置
        self.size_grip.move(self.width() - self.size_grip.width(),
                          self.height() - self.size_grip.height())
        # 调整字体大小以适应新的尺寸
        self.adjust_font_sizes()

    def show_color_dialog(self):
        dialog = QColorDialog(self.text_color, self)
        dialog.setWindowTitle("选择时钟颜色")
        dialog.setOption(QColorDialog.ColorDialogOption.ShowAlphaChannel)
        
        # 设置对话框样式
        dialog.setStyleSheet("""
            QColorDialog {
                background-color: #2c3e50;
            }
            QColorDialog QLabel {
                color: white;
            }
            QColorDialog QPushButton {
                background-color: #3498db;
                color: white;
                border: none;
                padding: 5px 15px;
                border-radius: 3px;
            }
            QColorDialog QPushButton:hover {
                background-color: #2980b9;
            }
            QColorDialog QLineEdit {
                background-color: #34495e;
                color: white;
                border: 1px solid #7f8c8d;
                padding: 3px;
            }
        """)
        
        if dialog.exec() == QColorDialog.DialogCode.Accepted:
            self.text_color = dialog.selectedColor()
            self.update_colors()  # 更新颜色
            # 同时更新按钮的颜色
            button_style = f"""
                QLabel {{
                    color: {self.text_color.name()};
                    background-color: rgba(255, 255, 255, 0.1);
                    border-radius: 10px;
                    font-size: 12px;
                    font-weight: bold;
                }}
                QLabel:hover {{
                    background-color: rgba(255, 255, 255, 0.2);
                }}
            """
            self.drag_handle.setStyleSheet(button_style)
            self.settings_button.setStyleSheet(button_style) 